package com.myrent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myrent.entity.EnterpriseMerchant;
import com.myrent.mapper.EnterpriseMapper;
import com.myrent.service.EnterpriseService;
import com.myrent.shiro.CustomizedToken;
import com.myrent.shiro.LoginType;
import com.myrent.utils.SaltUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;


@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, EnterpriseMerchant> implements EnterpriseService {

    @Override
    public boolean register(EnterpriseMerchant merchant) {
        String password = merchant.getEShopPassword();
        String salt = SaltUtil.produceSalt();
        ByteSource byteSource = ByteSource.Util.bytes(salt);
        SimpleHash simpleHash = new SimpleHash("md5", password, byteSource, SaltUtil.getEncryptNum());
        merchant.setEShopPassword(simpleHash.toHex());
        merchant.setSalt(salt);
        return save(merchant);
    }

    @Override
    public Boolean login(String eShopEmail, String eShopPassword) {
        Subject currentUser = SecurityUtils.getSubject();
        boolean b = currentUser.isAuthenticated();
        CustomizedToken token = new CustomizedToken(eShopEmail, eShopPassword, LoginType.Enterprise.toString());
        token.setRememberMe(false);
        try {
            currentUser.login(token);
        } catch (Exception e) {
            log.error("登录验证失败。用户名密码不匹配", e);
            return false;
        }
        return true;
    }

    @Override
    public EnterpriseMerchant getEnterprise(String eShopEmail) {
        QueryWrapper<EnterpriseMerchant> wrapper = new QueryWrapper<>();
        wrapper.eq("e_shop_email", eShopEmail);
        return getOne(wrapper, false);
    }

}
